// import { $getJson } from "./utils";
import { configure, BFSRequire } from 'browserfs'

interface Option {
  path: string
}

export const showImportJsonContextSymbol = Symbol('showImportJsonContextSymbol')
// const xhr = new XMLHttpRequest()
// xhr.open('GET', '../../public/json/', false)
// xhr.send()

// if (xhr.status === 200) {
//   console.log('%c [  ]-15', 'font-size:13px; background:#fb4dab; color:#ff91ef;', xhr)
// }
const demo = async () => {
  await configure({ fs: 'LocalStorage' }, () => {})

  const fs = BFSRequire('fs')

  // Now, you can write code like this:
  fs.readdir('../utils', function (err, files) {
    console.log('%c [  ]-26', 'font-size:13px; background:#fde976; color:#ffffba;', err, files)
  })
}

demo()

const GetJsonContextPromise = (pathName: any, path: string) => {
  return new Promise((resolve) => {
    $getJson(pathName, path).then((res: any) => {
      resolve({ [pathName]: res })
    })
  })
}

const $getJson = function (pathName: string, path: string) {
  return new Promise((resolve, reject) => {
    fetch(`${path}/${pathName}.json`)
      .then((res) => {
        return res.json()
      })
      .then((data) => {
        resolve(data)
      })
      .catch((error) => {
        reject(error)
      })
  })
}

const initGetJsonContext = async (option: Option): Promise<Record<string, any>> => {
  const { path } = option

  // const jsonContextModule = import.meta.glob(`${path}/*.json`, {
  //   eager: true
  // })

  // const promiseJsonArr = Object.keys(jsonContextModule).map((key: any) => {
  //   const allPathName = key.replace(path, '').replace('.json', '')

  //   return GetJsonContextPromise(allPathName, path)
  // })

  // const finalPromiseArr = promiseJsonArr.filter((item) => item !== null)

  // const jsonContext: any = {}

  // const res = await Promise.all(finalPromiseArr)

  // res.forEach((item) => {
  //   const key = Object.keys(item)[0]

  //   jsonContext[key] = item[key]
  // })

  // return jsonContext
}

export const initGetJsonContextTool = {
  install: (app, option) => {
    initGetJsonContext(option).then((jsonContext) => {
      app.provide(showImportJsonContextSymbol, jsonContext)
    })
  }
}

export default {
  install: (app, option) => {
    initGetJsonContext(option).then((jsonContext) => {
      app.provide(showImportJsonContextSymbol, jsonContext)
    })
  }
}
